//
//  CheckConnection.m
//  KotnetAutologin
//
//  monitoring the network connection
//
//  Created by Kristof Marien on 5/01/10.
//  Copyright 2010 KotnetAutologin. All rights reserved.
//

#import "CheckConnection.h"

static void DefaultRouteHasChanged(SCDynamicStoreRef store, CFArrayRef changedKeys, void *info) {
	CheckConnection *self = (CheckConnection *)info;
	[self check:YES];
}

@implementation CheckConnection

@synthesize delegate;
@synthesize connectedCallback;
@synthesize notconnectedCallback;
/**
 *  starts checking
 */
- (void) isConnected:(id)connectionDelegate connectedSelector:(SEL)connectedSelector notconnectedSelector:(SEL)notconnectedSelector
{
	self.delegate = connectionDelegate;
	self.connectedCallback = connectedSelector;
	self.notconnectedCallback = notconnectedSelector;
	
	[self check:NO];
}
/**
 *  check now and execute delegate
 */
- (void) check:(BOOL)once
{
	if ([self isNetworked]) {
		if (self.delegate && self.connectedCallback) {
			if ([self.delegate respondsToSelector:self.connectedCallback]) {
				[self.delegate performSelector:self.connectedCallback];
			}
		}
	} else {
		if (self.delegate && self.notconnectedCallback) {
			if ([self.delegate respondsToSelector:self.notconnectedCallback]) {
				[self.delegate performSelector:self.notconnectedCallback];
			}
		}
	}
	if (!once)
		[self checkNetwork];
}
/**
 *  check networkconnection
 */
- (BOOL) isNetworked
{
    CFStringRef result = NULL;
	BOOL isNetwork = NO;
	
    SCDynamicStoreRef dynamicStore = SCDynamicStoreCreate(NULL, CFSTR("KotnetAutologin"), NULL, NULL);
    if (dynamicStore != NULL) {
		CFDictionaryRef properties = (CFDictionaryRef)
		SCDynamicStoreCopyValue(dynamicStore, CFSTR("State:/Network/Global/IPv4"));
		if (properties != NULL) {
			result = (CFStringRef) CFDictionaryGetValue(properties, CFSTR("Router"));
			if (result != NULL) {
				CFRetain(result);
				isNetwork = YES;
			}
			CFRelease(properties);
		}
		CFRelease(dynamicStore);
    }
	
	return isNetwork;
}
/**
 *  starts monitoring
 */
- (void) checkNetwork
{
	if (checkingNetwork)
		return;
	
	checkingNetwork = YES;
	
	SCDynamicStoreContext context = {0, self, NULL, NULL, NULL};
	SCDynamicStoreRef gDynamicStore = SCDynamicStoreCreate(NULL, CFSTR("KotnetAutologin"), DefaultRouteHasChanged, &context);
	
	CFStringRef key = SCDynamicStoreKeyCreate(NULL, CFSTR("%@/%@/%@/%@"), kSCDynamicStoreDomainState, kSCCompNetwork, kSCCompGlobal, kSCEntNetIPv4);
	
	CFArrayRef keyArray = CFArrayCreate(NULL, (const void **)&key, 1, &kCFTypeArrayCallBacks);
	SCDynamicStoreSetNotificationKeys(gDynamicStore, keyArray, NULL);
	CFRelease(keyArray);
	CFRelease(key);
	
	CFRunLoopSourceRef runLoopSource = SCDynamicStoreCreateRunLoopSource(NULL, gDynamicStore, 0);
	CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
	CFRelease(runLoopSource);
}

@end
